/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainWindow.java
 *
 * Created on 26.11.2008, 12:21:53
 */
package org.csm.csmstaffhelper.gui;

import com.sun.java.swing.plaf.windows.resources.windows_de;
import java.awt.AWTException;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.csm.csmstaffhelper.CsmProperties;
import org.csm.csmstaffhelper.StaffSearcher;

/**
 *
 * @author exception
 */
public class MainWindow extends javax.swing.JFrame {

    private Timer searchTask = null;
    private Timer progressBarTask = null;
    
    private static void initSystemTrayIcon(final MainWindow window) throws HeadlessException {
        final TrayIcon trayIcon;
        if (SystemTray.isSupported()) {
            SystemTray tray = SystemTray.getSystemTray();
            Image image = Toolkit.getDefaultToolkit().getImage("icon.png");
            MouseListener mouseListener = new MouseListener() {

                public void mouseClicked(MouseEvent e) {
                    window.setVisible(!window.isVisible());
                }

                public void mouseEntered(MouseEvent e) {
                    // No op
                }

                public void mouseExited(MouseEvent e) {
                    // No op
                }

                public void mousePressed(MouseEvent e) {
                    // No op
                }

                public void mouseReleased(MouseEvent e) {
                    // No op
                }
            };
            ActionListener exitListener = new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            };
            PopupMenu popup = new PopupMenu();
            MenuItem defaultItem = new MenuItem("Exit");
            defaultItem.addActionListener(exitListener);
            popup.add(defaultItem);
            trayIcon = new TrayIcon(image, "CSM Staff Helper", popup);

//            ActionListener actionListener = new ActionListener() {
//
//                public void actionPerformed(ActionEvent e) {
//                    trayIcon.displayMessage("Action Event", "An Action Event Has Been Performed!", TrayIcon.MessageType.INFO);
//                }
//            };

            trayIcon.setImageAutoSize(true);
//            trayIcon.addActionListener(actionListener);
            trayIcon.addMouseListener(mouseListener);
            try {
                tray.add(trayIcon);
            } catch (AWTException e) {
                System.err.println("TrayIcon could not be added.");
            }
        }
    }

    public void printText(String text) {
        textArea.setText(textArea.getText() + text + "\n");
    }

    public void moveProgressBar() {
        if(progressBar.getValue() == progressBar.getMaximum()) {
            progressBar.setValue(progressBar.getMinimum());
        }

        progressBar.setValue(progressBar.getValue() + 1);
    }

    /** Creates new form MainWindow */
    public MainWindow() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();
        progressBar = new javax.swing.JProgressBar();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        optionButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("CSM Staff Search Helper");
        setIconImage(getIconImage());
        setResizable(false);

        jButton1.setText("About");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Close");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        textArea.setColumns(20);
        textArea.setEditable(false);
        textArea.setRows(5);
        jScrollPane1.setViewportView(textArea);

        jButton3.setText("Start");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Stop");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        optionButton.setText("Options");
        optionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optionButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton3)
                .addGap(2, 2, 2)
                .addComponent(jButton4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(optionButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 95, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(optionButton)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
//        AboutWindow aboutWindow = new AboutWindow();
//        aboutWindow.setVisible(true);
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                AboutWindow win = new AboutWindow();
                win.setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png"));
                
                win.setVisible(true);
            }
        });
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        try {
            final MainWindow win = this;
            final CsmProperties props = new CsmProperties();
            final StaffSearcher searcher = new StaffSearcher(props);
            printText("Staff search started...");
            printText("You search staff with levels: " + props.getBaseLevel());
            printText("Stricted search mode is " + (props.getStricted() == true ? "on" : "off"));
            searchTask = new Timer();
            progressBarTask = new Timer();

            searchTask.schedule(new TimerTask() {

                @Override
                public void run() {
                    try {
                        boolean found = searcher.searchStaff(win);
                        if(found == false) {
                            printText("During these " + props.getMinutes() + " minutes there is no result.");
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (URISyntaxException ex) {
                        Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }, 1000, props.getMinutes() * 60 * 1000);

            progressBar.setMaximum(props.getMinutes() * 60);

            progressBarTask.schedule(new TimerTask() {

                @Override
                public void run() {
                    moveProgressBar();
                }
            }, 0, 1000);
            
            optionButton.setEnabled(false);
        } catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void optionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optionButtonActionPerformed
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    OptionWindow win = new OptionWindow();
                    win.setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png"));
                    win.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
}//GEN-LAST:event_optionButtonActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        if(searchTask != null) {
            searchTask.cancel();
            progressBarTask.cancel();

            searchTask = null;
            progressBarTask = null;
            
            optionButton.setEnabled(true);

            printText("Staff search stopping...");

            progressBar.setValue(progressBar.getMinimum());
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws IOException {
        final MainWindow window = new MainWindow();
        window.setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png"));

        initSystemTrayIcon(window);

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                window.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton optionButton;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JTextArea textArea;
    // End of variables declaration//GEN-END:variables
}
